import uploadModel from '../model/uploadModel';
import { fileSuffixIcon } from './util';
/*
 * 上传
 * @param {file} file 文件
 * @param {Object} options 上传参数
 * @returns {*}
 */
export function upload(compressFile, options) {
  // 系统变量获取文件最大上传的大小
  const sysconfigSize = JE.systemConfig.JE_SYS_MAX_UPLOAD_SIZE || 100;
  // 获取当前文件的大小
  const { size } = compressFile;

  // 将当前的文件大小的单位转化
  const formatSise = (size / (1024 * 1024)).toFixed(2);
  if (parseFloat(formatSise) > parseInt(sysconfigSize, 10)) {
    JE.msg(`文件不可超过${sysconfigSize}MB`);
    return false;
  }

  const {
    diskType,
    nodeId,
  } = options;
  compressFile.fileType = 'dir';
  const formData = new FormData();
  formData.append('files', compressFile.fileObj || compressFile);
  formData.append('diskType', diskType);
  formData.append('nodeId', options.fileType == 'dir' ? compressFile.nodeId : nodeId);
  const headers = {
    'Platform-Agent': 'AppleWebKit/537.36 (KHTML, like Gecko)',
    authorization: JE.getCookies('authorization'),
  };
  const requset = jQuery.ajax({
    type: 'POST',
    url: `je/disk/file?size=${size}`,
    data: formData, // 这里上传的数据使用了formData 对象
    processData: false, // 必须false才会自动加上正确的Content-Type
    contentType: false,
    headers,
    // 这里我们先拿到jQuery产生的XMLHttpRequest对象，为其增加 progress 事件绑定，然后再返回交给ajax使用
    xhr() {
      const xhr = jQuery.ajaxSettings.xhr();
      if (xhr.upload) {
        // 侦查附件上传情况 ,这个方法大概0.05-0.1秒执行一次
        xhr.upload.addEventListener('progress', (evt) => {
          const {
            loaded,
          } = evt; // 已经上传大小情况
          const tot = evt.total; // 附件总大小
          const per = Math.floor(100 * loaded / tot); // 已经上传的百分比
          options.progress.call(requset, per, compressFile, options.parentPathName);
        }, false);
        return xhr;
      }
    },
    // 上传成功后回调
    success(data) {
      if (data.success) {
        // const res = data.obj;
        data.obj[0].UUID = compressFile.uuid;
        options.callback(data);
      } else {
        data.UUID = compressFile.uuid;
        options.callback(data);
      }
    },

    // 上传失败后回调
    error(error) {
      const errObj = {
        err: true,
        UUID: compressFile.uuid,
      };
      options.callback(errObj);
      return error;
    },
  });
  return requset;
}

// eslint-disable-next-line import/prefer-default-export
export function uploadFile(options, type) {
  return new Promise((resolve) => {
    const requestMap = {};
    const {
      path,
    } = options;
    const files = path;
    if (JE.isEmpty(files) && !type) {
      // eslint-disable-next-line no-new
      new UploadUtil({
        multiple: options.multiple,
        callback(files) {
          options.path = files;
          uploadFile(options);
        },
      });
      resolve(requestMap);
    } else {
      // if (files.length > 6) {
      //   JE.msg('最多同时上传6个文件');
      // }
      for (let i = 0; i < files.length; i++) {
        const file = files[i];
        file.uuid = JE.uuid();
        requestMap[file.uuid] = upload(file, options);
      }
      // console.log(`结束的参数: ${tt}`, options, type, requestMap);
      resolve(requestMap);
    }
  });
}

/**
 * 上传中的方法
 *
 * @export
 * @param {Object} params 上传中的传递参数
 */
export function uploadingFunc(params) {
  const FileName = params.file.name;
  const index1 = FileName.lastIndexOf('.') + 1;
  const index2 = FileName.length;
  const suffixFile = FileName.substring(index1, index2);// 后缀名
  // 格式化上传的数据
  let paramsStyle = {}; // 格式化的数据
  paramsStyle.name = params.file.name || '没能获取到';
  paramsStyle.size = params.file.size;
  paramsStyle.icon = fileSuffixIcon(suffixFile);
  paramsStyle.uploadTime = params.file.lastModified;
  paramsStyle.docSrc = params.pathName;
  paramsStyle.UUID = params.file.uuid;
  paramsStyle.uploadStatus = params.res == 100 ? 99 : params.res;
  paramsStyle.uploadIssue = 'ok';
  paramsStyle = uploadModel.create(paramsStyle);
  let arr = JSON.parse(sessionStorage.getItem('docUploadArr')) || [];
  const UUIDArr = arr.map(item => item.UUID);
  !UUIDArr.includes(params.file.uuid) && arr.push(paramsStyle);
  arr = arr.map((arrData) => {
    let dd = {};
    if (arrData.UUID == params.file.uuid) {
      dd = paramsStyle;
    } else {
      dd = arrData;
    }
    return dd;
  });
  params.res <= 100 && sessionStorage.setItem('docUploadArr', JSON.stringify(arr));
}

/**
 * 上传完成之后的callback回调
 *
 * @export
 * @param {Object} params 上传完成的的回调参数
 */
export function uploadEnd(params) {
  let arr = JSON.parse(sessionStorage.getItem('docUploadArr'));
  if (!arr) return;
  arr = arr.filter((arrData) => {
    if (arrData.UUID != params.UUID) {
      return arrData;
    }
  });
  sessionStorage.setItem('docUploadArr', JSON.stringify(arr));
}

class UploadUtil {
  className = '__je-upload__';

  el = null;

  multiple = false;

  constructor(options) {
    this.multiple = options.multiple;
    options.callback && (this.callback = options.callback);
    return this.createEl();
  }

  createEl() {
    // 创建元素
    let el = this.getUploader();
    if (el) {
      return el;
    }
    el = document.createElement('input');
    el.setAttribute('type', 'file');
    // el.setAttribute('webkitdirectory', true);
    // el.setAttribute('directory', true);
    // el.setAttribute('mozdirectory', true);
    el.setAttribute('class', this.className);
    this.multiple && el.setAttribute('multiple', this.multiple);
    this.el = el;
    this.initEvents();
    return this.getUploader();
  }

  // 返回上传器
  getUploader() {
    return this.el;
  }

  initEvents() {
    const el = this.getUploader();
    el.value = null;
    el.addEventListener('change', (e) => {
      const {
        files,
      } = e.target;
      this.callback(files);
    });
    el.click();
  }
}
